package com.cloudcc.boot.utils.backup;

import com.cloudcc.boot.model.UserInfo;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class ExoprtCode {

//	public static String env = "http://crm.lshmec.com";
//	public static String folder = "C:\\神州云动\\利星行配置备份";
//	public static String username = "ebdpsd@cloudcc.com";
//	public static String password = "ebdpsd222";

//	public static String env = "http://app1a.cloudcc.com";
//	public static String folder = "C:\\神州云动\\利星行配置备份";
//	public static String username = "admin@tkxiangbian-demo.com";
//	public static String password = "admin@tkxiangbian-demo.com123";
//	public static String env = "http://10.51.3.176";
//	public static String folder = "C:\\神州云动\\国药控股配置测试库备份";
	public static String env = "https://k8smt01.cloudcc.com";
	public static String folder = "C:\\神州云动\\惠科正式库备份";
	public static String username = "admin@totalenergies.com";
	public static String password = "admin1234";
//	public static String env = "https://crm.sinopharmholding-fl.com/";
//	public static String folder = "C:\\神州云动\\国药控股配置正式库备份";
//	public static String username = "ghc@cloudcc.com";
//	public static String password = "cloudcc@2021";

	public static void main(String[] a) throws IOException {
		UserInfo uInfo = new UserInfo(username, password);

//		String userinfoStr = Util.getBinding(env, "admin01@dev-sales.com", "999999");
//		System.out.println(userinfoStr);
//		JSONObject userInfo = JSONObject.fromObject(userinfoStr);
//		String binding = (String) userInfo.get("binding");


		String allCodeStr = Util.invokeCrm(uInfo,env);
//		System.out.println("allCodeStr:"+allCodeStr);
//		allCodeStr = new String(allCodeStr.getBytes("ISO-8859-1"),"utf-8");
		JSONObject allCode = JSONObject.fromObject(allCodeStr);
		JSONArray triggers = allCode.getJSONArray("triggers");
		JSONArray fags = allCode.getJSONArray("fags");
		JSONArray ccpeaks = allCode.getJSONArray("ccpeaks");
		JSONArray visualPages = allCode.getJSONArray("visualPages");
		JSONArray buttons = allCode.getJSONArray("buttons");
		JSONArray components = allCode.getJSONArray("components");
		JSONArray schemetables = allCode.getJSONArray("schemetables");
		JSONArray validateRules = allCode.getJSONArray("validateRules");


		// 删除原来的文件
		File root = new File(folder);
		if (root.exists()) {
			// 如果要删除代码文件夹，把这句注释去掉
			deleteDir(root);
		}

		for (int i = 0; i < triggers.size(); i++) {
			JSONObject o = triggers.getJSONObject(i);
			String path = folder + "/触发器/" + o.getString("label").trim() + "/" + o.getString("trigger_time").trim() + "/";
			File dir = new File(path);
			dir.mkdirs();
			File f = new File(path + o.getString("name").trim().replaceAll("[^0-9a-zA-Z\u4e00-\u9fa5.，,。？“”]+","") + ".java");
			if (f.exists()) {

				try {
					f.delete();
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}

			}
			FileOutputStream out = new FileOutputStream(f);
			IOUtils.write(o.getString("trigger_source").getBytes(), out);
		}

		for (int i = 0; i < fags.size(); i++) {
			JSONObject o = fags.getJSONObject(i);
			String path = folder + "/类/";
			File dir = new File(path);
			dir.mkdirs();
			File f = new File(path + o.getString("name").trim().replaceAll("[^0-9a-zA-Z\u4e00-\u9fa5.，,。？“”]+","") + ".java");
			if (f.exists()) {
				f.delete();
			}
			FileOutputStream out = new FileOutputStream(f);
			IOUtils.write(o.getString("source").getBytes(), out);
		}

		for (int i = 0; i < ccpeaks.size(); i++) {
			JSONObject o = ccpeaks.getJSONObject(i);
			String path = folder + "/定时类/";
			File dir = new File(path);
			dir.mkdirs();
			File f = new File(path + o.getString("name").trim().replaceAll("[^0-9a-zA-Z\u4e00-\u9fa5.，,。？“”]+","") + ".java");
			if (f.exists()) {
				f.delete();
			}
			FileOutputStream out = new FileOutputStream(f);
			IOUtils.write(o.getString("source").getBytes(), out);
		}

		for (int i = 0; i < visualPages.size(); i++) {
			JSONObject o = visualPages.getJSONObject(i);
			String subfolder = o.optString("foldername");
			if (StringUtils.isBlank(subfolder) || "null".equals(subfolder)) {
				subfolder = "未归档页面文件夹";
			}
			String path = folder + "/页面/" + subfolder + "/";
			File dir = new File(path);
			dir.mkdirs();
			File f = new File(path +  o.getString("label").trim().replaceAll("[^0-9a-zA-Z\u4e00-\u9fa5.，,。？“”]+","") + "_" + o.getString("name").trim()  + ".java");
			if (f.exists()) {
				f.delete();
			}
			FileOutputStream out = new FileOutputStream(f);
			IOUtils.write(o.getString("page_source").getBytes(), out);
		}

		for (int i = 0; i < buttons.size(); i++) {
			JSONObject o = buttons.getJSONObject(i);
			String path = folder + "/按钮和链接/" + o.getString("objname").trim() + "/";
			;
			File dir = new File(path);
			dir.mkdirs();
			File f = new File(
					path + o.getString("label").trim().replaceAll("[^0-9a-zA-Z\u4e00-\u9fa5.，,。？“”]+","") + "_" + o.getString("name").trim() + "_" + o.getString("btn_type") + ".java");
			if (f.exists()) {
				f.delete();
			}
			FileOutputStream out = new FileOutputStream(f);
			if ("URL".equals(o.getString("event").trim())) {
				IOUtils.write(o.getString("url").getBytes(), out);
			} else {
				IOUtils.write(o.getString("function_code").getBytes(), out);
			}

		}

		for (int i = 0; i < components.size(); i++) {
			JSONObject o = components.getJSONObject(i);
			String path = folder + "/主页组件/";
			File dir = new File(path);
			dir.mkdirs();
			File f = new File(path + o.getString("name").trim().replaceAll("[^0-9a-zA-Z\u4e00-\u9fa5.，,。？“”]+","") + ".java");
			if (f.exists()) {
				f.delete();
			}
			FileOutputStream out = new FileOutputStream(f);
			IOUtils.write(o.getString("content").getBytes(), out);
		}


		for (int i = 0; i < schemetables.size(); i++) {
			JSONObject o = schemetables.getJSONObject(i);
			String path = folder + "/字段/" + o.getString("label").trim()+"_"+o.getString("apiname").trim() + "/";
			;
			File dir = new File(path);
			dir.mkdirs();
			File f = new File(
					path + o.getString("schemefield_name").trim().replaceAll("[^0-9a-zA-Z\u4e00-\u9fa5.，,。？“”]+","") + ".java");
			if (f.exists()) {
				f.delete();
			}
			FileOutputStream out = null;
			try {
				out = new FileOutputStream(f);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			IOUtils.write((o.getString("expression")+"\r\n"+o.getString("execute_expression")).getBytes(), out);

		}

		for (int i = 0; i < validateRules.size(); i++) {
			JSONObject o = validateRules.getJSONObject(i);
			String path = folder + "/验证规则/" + o.getString("label").trim()+"_"+o.getString("schemetable_name").trim() + "/";
			;
			File dir = new File(path);
			dir.mkdirs();
			File f = new File(
					path + o.getString("name").trim().replaceAll("[^0-9a-zA-Z\u4e00-\u9fa5.，,。？“”]+","") + ".java");
			if (f.exists()) {
				f.delete();
			}
			FileOutputStream out = new FileOutputStream(f);
			IOUtils.write((o.getString("function_code")+"\r\n"+o.getString("error_message")+"\r\n"+o.getString("description")).getBytes(), out);

		}


	}

	/**
	 * 删除空目录
	 *
	 * @param dir
	 *            将要删除的目录路径
	 */
	private static void doDeleteEmptyDir(String dir) {
		boolean success = (new File(dir)).delete();
		if (success) {
			System.out.println("Successfully deleted empty directory: " + dir);
		} else {
			System.out.println("Failed to delete empty directory: " + dir);
		}
	}

	/**
	 * 递归删除目录下的所有文件及子目录下所有文件
	 *
	 * @param dir
	 *            将要删除的文件目录
	 * @return boolean Returns "true" if all deletions were successful. If a
	 *         deletion fails, the method stops attempting to delete and returns
	 *         "false".
	 */
	private static boolean deleteDir(File dir) {
		if (dir.isDirectory()) {
			String[] children = dir.list();
			// 递归删除目录中的子目录下
			for (int i = 0; i < children.length; i++) {
				boolean success = deleteDir(new File(dir, children[i]));
				if (!success) {
					return false;
				}
			}
		}
		// 目录此时为空，可以删除
		return dir.delete();
	}

}
